﻿using System;
using System.Collections.Generic;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	public class HYRotateFamily : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException();
				}
				UIApplication application = commandData.Application;
				Document document = application.ActiveUIDocument.Document;
				Selection selection = application.ActiveUIDocument.Selection;
				for (;;)
				{
					transaction = new Transaction(document, "45°旋转实体");
					transaction.Start();
					RevitVersionFuncs.ClearSelection(selection);
					string text = "请选择要旋转的实体集合，其中必须包含一个族实例，且只可有一个族实例……";
					IList<Element> list = new List<Element>();
					list = selection.PickElementsByRectangle(text);
					if (list.Count <= 0)
					{
						break;
					}
					FamilyInstance familyInstance = null;
					ICollection<ElementId> collection = new List<ElementId>();
					foreach (Element element in list)
					{
						if (element is FamilyInstance)
						{
							familyInstance = (element as FamilyInstance);
						}
						collection.Add(element.Id);
					}
					if (familyInstance == null)
					{
						goto Block_7;
					}
					XYZ point = (familyInstance.Location as LocationPoint).Point;
					point.Add(new XYZ(0.0, 0.0, 1.0));
					Line line = document.CreatYJKLine(point, new XYZ(0.0, 0.0, 1.0), false);
					line.MakeUnbound();
					double num = 0.78539816339744828;
					ElementTransformUtils.RotateElements(document, collection, line, num);
					document.Regenerate();
					transaction.Commit();
				}
				YJKMessageBox.Show("未选中一个旋转实体，\n请重新选择实体");
				return Autodesk.Revit.UI.Result.Failed;
				Block_7:
				YJKMessageBox.Show("必须有一个族实例实体，\n请重新选择实体");
				result = Autodesk.Revit.UI.Result.Failed;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
					if (status == 1)
					{
						transaction.Commit();
					}
					else if (status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
